package com.ruoyi.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 自动填充通用字段
 *
 * @author yr
 */
@Component
public class MetaHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Date date = new Date();
        this.setFieldValByName("createTime", date, metaObject);
        this.setFieldValByName("updateTime", date, metaObject);
        this.setFieldValByName("delFlag", "0", metaObject);
        Object createBy = this.getFieldValByName("createBy", metaObject);
        if (createBy == null || "".equals(createBy)) {
            this.setFieldValByName("createBy", getUserId(), metaObject);
            this.setFieldValByName("updateBy", getUserId(), metaObject);
        }
        Object entId = this.getFieldValByName("entId", metaObject);
        if (entId == null || "".equals(entId)) {
            this.setFieldValByName("firmId", getFirmId(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);
        Object updateBy = this.getFieldValByName("updateBy", metaObject);
        if (updateBy == null || "".equals(updateBy)) {
            this.setFieldValByName("updateBy", getUserId(), metaObject);
        }
    }

    /**
     * 获取用户缓存信息
     */
    public LoginUser getLoginUser() {
        try {
            return (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取登录用户id
     */
    public Long getUserId() {
        LoginUser loginUser = getLoginUser();
        if (loginUser == null){
            return 1L;
        }
        return loginUser.getUserId();
    }

    /**
     * 获取登录部门id
     */
    public Long getDeptId() {
        return getLoginUser().getDeptId();
    }

    /**
     * 获取登录用户当前工厂
     */
    public String getFirmId() {
//        return getLoginUser().getFirmId();
        return "0";
    }

}
